<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="container">
          <el-form inline size="small" :model="from" ref="from" :label-position="labelPosition" label-width="100px">
            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="20" :xl="20">
                <el-form-item label="主账号">
                  <el-input v-model="from.account" placeholder="请输入账号" clearable class="selWidth" />

                  <!-- 更改搜索输入框 -->
                  <!-- <UserSearchable v-model="from.account" :label="from.nickname" type=""></UserSearchable> -->
                </el-form-item>

                <el-form-item label="登录状态">
                  <el-select v-model="from.status" placeholder="请选择" class="selWidth" style="width: 100px;">
                    <el-option :value="1" label="在线"></el-option>
                    <el-option :value="2" label="离线"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="分组">
                  <el-select v-model="from.groupId" placeholder="请选择分组"  clearable>
                    <el-option :value="item.id" v-for="(item, index) in groupList" :key="index"
                      :label="item.groupName"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="标签">
                  <el-select multiple v-model="searchFrom.tagId" placeholder="请选择标签" clearable>
                    <el-option :value="item.id" v-for="(item, index) in labelLists" :key="index"
                      :label="item.name"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="24" :md="24" :lg="3" :xl="3" class="text-right from">
                <el-form-item>
                  <el-button class="mr10" size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
                  <el-button class="mr10" size="small" icon="el-icon-refresh" @click="reset()">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="btn_bt">
          <el-button class="mr10" size="small" type="primary" icon="el-icon-circle-plus-outline" @click="add()">新增</el-button>
          <el-button class="mr10" size="small" type="danger" icon="el-icon-delete" @click="allDel()">删除</el-button>
        </div>
      </div>
      <el-table border ref="table" v-loading="loading" :data="tableData.data" style="width: 100%" size="mini"
        @selection-change="onSelectTab" highlight-current-row>
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="id" label="ID" min-width="80" />
        <el-table-column prop="adminName" label="所属代理" min-width="80" />
        <el-table-column prop="account" label="主账号" min-width="80" />
        <el-table-column prop="futuresMerchantName" label="期货公司" min-width="120" />
        <el-table-column prop="interfaceTypeName" label="接口类型" min-width="120">
          <template slot-scope="scope">
            {{ selectinterfacetype(scope.row.interfaceType) }}
          </template>
        </el-table-column>
        <el-table-column prop="nowadayEquity" label="当前权益" min-width="120" />
        <el-table-column prop="loginLog" label="登录说明" min-width="120" />
        <el-table-column prop="status" label="状态" min-width="120">
          <template slot-scope="scope">
            <span :style="scope.row.status == 1 ? 'color:red' : ''">{{
              scope.row.status == 1 ? "在线" : "离线"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isLogin" label="自动登录" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.isLogin == 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column prop="secondaryVerification" label="二次登录" min-width="120" />
        <el-table-column label="操作" min-width="300" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleLogin(scope.row)">登录</el-button>
            <el-button type="warning" size="mini" @click="handleLogout(scope.row)">登出</el-button>
            <!-- <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleDel(scope.row)">删除</el-button> -->
            <!-- 更多 -->
            <el-dropdown>
              <span class="el-dropdown-link">
                更多<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleEdit(scope.row)">编辑</el-dropdown-item>
                <!-- <el-dropdown-item @click.native="setGroup(scope.row)">分组</el-dropdown-item>
                <el-dropdown-item @click.native="setLabel(scope.row)">标签</el-dropdown-item> -->
                <el-dropdown-item @click.native="setBatch('group', scope.row)"
                  v-if="checkPermi(['admin:user:group'])">分组</el-dropdown-item>
                <el-dropdown-item @click.native="setBatch('label', scope.row)"
                  v-if="checkPermi(['admin:user:tag'])">标签</el-dropdown-item>
                <el-dropdown-item @click.native="handleDel(scope.row)">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination :page-sizes="[15, 30, 45, 60]" :page-size="from.limit" :current-page="from.page"
          layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="handleSizeChange"
          @current-change="pageChange" />
      </div>
    </el-card>

    <el-dialog title="钱包出入金" :visible.sync="mVisible" width="40%" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :rules="mrules" ref="mform" :model="mform" label-width="120px">
        <el-form-item label="钱包：" prop="walletResponses">
          <div v-for="(item, index) in mform.walletResponses" :key="index">
            <span>{{ item.currencyName }}</span>
            <span style="margin-left: 10px">{{ item.balance }}</span>
          </div>
        </el-form-item>
        <el-form-item label="币种：" prop="currencyId">
          <el-select v-model="mform.currencyId" placeholder="请选择币种">
            <el-option v-for="item in walletResponses" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="进出类型：" prop="inOutType">
          <el-radio-group v-model="mform.inOutType">
            <el-radio :label="1">入额</el-radio>
            <el-radio :label="2">出额</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="mform.amount" type="number" placeholder="请输入金额" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="mClose()">取 消</el-button>
        <el-button type="primary" @click="mSubmit()">确 定</el-button>
      </span>
    </el-dialog>

    <!--用户列表-->
    <el-dialog title="用户列表" :visible.sync="userVisible" width="900px" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <user-list v-if="userVisible" @getTemplateRow="getTemplateRow"></user-list>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userclose()">取 消</el-button>
        <el-button type="primary" @click="usersubmit()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="ruleForm.id ? '编辑' : '新增'" :visible.sync="dialogVisible" width="700px"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :rules="ruleFormrules" ref="ruleForm" :model="ruleForm" label-width="180px">
        <el-form-item label="用户名" prop="account">
          <el-input v-model="ruleForm.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="授权码" prop="authorizationCode">
          <el-input type="textarea" v-model="ruleForm.authorizationCode"></el-input>
        </el-form-item>
        <el-form-item label="APPID">
          <el-input v-model="ruleForm.appId"></el-input>
        </el-form-item>
        <el-form-item label="交易接口" prop="interfaceType">
          <el-select v-model="ruleForm.interfaceType" placeholder="请选择" class="selWidth" clearable>
            <el-option v-for="item in interfacetypeList" :key="item.dictValue" :value="item.dictValue"
              :label="item.dictLabel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易商" prop="futuresMerchantId">
          <el-select v-model="ruleForm.futuresMerchantId" placeholder="请选择" class="selWidth" clearable>
            <el-option v-for="item in futuresmerchant" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
    <!--实盘登录-->
    <el-dialog title="实盘登录" :visible.sync="masteraccountVisible" width="400px" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <span>手机号</span><el-input disabled v-model="masteraccountLoginForm.phone"></el-input>
      <span>验证码</span>
      <el-input v-model="masteraccountLoginForm.verifyCode" placeholder="输入验证码">
        <el-button slot="append" @click="sendMsg">{{
          countdown == 60 ? "发送验证码" : countdown + "后重新发送"
        }}</el-button>
      </el-input>
      <el-checkbox v-model="masteraccountLoginForm.loginType">是否信任该设备</el-checkbox>
      <span slot="footer" class="dialog-footer">
        <el-button @click="loginClose()">取 消</el-button>
        <el-button type="primary" @click="loginSubmit()" :loading="loginLoading">{{ loginLoading ? "登录中,请稍候" : "提交验证码"
          }}</el-button>
      </span>
    </el-dialog>

    <!-- 分组/标签 -->
    <el-dialog title="设置分组" :visible.sync="setVisible" width="25%">
      <div>
        <span>分组:</span>
        <el-select v-model="setId" placeholder="请选择分组" class="selWidth m-left-20" clearable>
          <el-option v-for="item in setoptions" :key="item.id" :label="item.groupName" :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureSet">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="设置" :visible.sync="setdialogVisible" width="500px" :before-close="handleClose">
      <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic"
        v-loading="loading">
        <el-form-item prop="groupId" label="用户分组" :rules="[
          { required: true, message: '请选择用户分组', trigger: 'change' },
        ]" v-if="batchName === 'group'" key="1">
          <el-select v-model="dynamicValidateForm.groupId" placeholder="请选择分组" style="width: 80%" filterable>
            <el-option :value="item.id" v-for="(item, index) in groupList" :key="index"
              :label="item.groupName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="groupId" label="用户标签" :rules="[
          { required: true, message: '请选择用户标签', trigger: 'change' },
        ]" v-else>
          <el-select filterable allow-create multiple v-model="dynamicValidateForm.groupId" placeholder="请选择标签"
            style="width: 80%">
            <el-option :value="item.id" v-for="(item, index) in labelLists" :key="index" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('dynamicValidateForm')">确 定</el-button>
      </span>
    </el-dialog>



  </div>
</template>

<script>
import userList from "@/components/userList";

import UserSearchable from "@/components/UserSearchable";

import {
  traderconfigtemplateGetOption, // 交易员综合配置模版全列表
  exchangefeetemplateGetOption, // 交易员手续费模板全列表
  traderrisktemplateGetOption, // 交易员风控模板全列表
} from "@/api/agent";
import { datafieldGetOption } from "@/api/dataField";

import { checkPermi } from "@/utils/permission"; // 权限判断函数

import { interfacetypeGetOption as interfacetype } from "@/api/transaction";
import {
  userListApi,
  masteraccountList,
  masteraccountSave,
  masteraccountInfo,
  masteraccountUpdate,
  masteraccountDelete,
  traderaccountExport,
  sys_dict_dataTypeCurrency,
  traderaccountInOutType,
  interfaceTrader,
  getLoginInfo,
  resendVerifyCode,
  masteraccountVerify,
  masteraccountLogin,
  masteraccountLogout,
  tagListApi,
  groupListApi,
  groupPiApi,
  tagPiApi,
} from "@/api/user";
import { Message } from "element-ui";
import { search } from "core-js/fn/symbol";
export default {
  name: "trader",
  components: {
    userList,
    UserSearchable,
  },
  data() {
    return {
      options: [],
      labelPosition: "right",
      userVisible: false,
      countdown: 60,
      masteraccountVisible: false,
      masteraccountLoginForm: {
        loginType: 2,
      },
      loginTimer: null,
      smsTimer: null,
      loginTimeCount: 0,
      loginLoading: false,
      sendLoading: false,
      from: {
        status:1,
        account: "",
        // isLogin: 1,
        page: 1,
        limit: 15,
        tagId:"",
        groupId: ""
      },
      searchFrom: {
        tagId: [],
      },
      loading: false,
      tableData: {
        data: [],
        total: 0,
      },
      selection: [],
      walletResponses: [],
      mform: {
        traderAccountId: "",
        inOutType: "",
        walletResponses: [],
        currencyId: "",
        amount: "",
      },
      mVisible: false,
      dialogVisible: false,
      exchangeFeeOptions: [],
      traderConfigOptions: [],
      traderriskOptions: [],
      interfacetypeList: [],
      futuresmerchant: [],
      ruleForm: {
        id: "",
        userId: "",
        traderConfigTemplateId: "",
        exchangeFeeTemplateId: "",
        traderRiskTemplateId: "",
        accountType: "",
        tradeType: "",
        status: 1,
        remark: "",
      },

      ruleFormrules: {
        account: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
        authorizationCode: [
          {
            required: true,
            message: "请输入授权码",
            trigger: "blur",
          },
        ],
        interfaceType: [
          {
            required: true,
            message: "请选择交易接口",
            trigger: "change",
          },
        ],
        futuresMerchantId: [
          {
            required: true,
            message: "请选择交易商",
            trigger: "change",
          },
        ]

      },

      mrules: {
        currencyId: [
          {
            required: true,
            message: "请选择币种",
            trigger: "change",
          },
        ],
        inOutType: [
          {
            required: true,
            message: "请选择进出类型",
            trigger: "change",
          },
        ],
        amount: [
          {
            required: true,
            message: "请输入金额",
            trigger: "blur",
          },
        ],


      },
      checkedCities: [],
      cities: [
        { id: 1, label: "国内" },
        { id: 2, label: "国际" },
      ],
      rules: {
        userId: [
          {
            required: true,
            message: "请选择用户",
            trigger: "change",
          },
        ],
        traderConfigTemplateId: [
          {
            required: true,
            message: "请选择交易员综合配置模板",
            trigger: "change",
          },
        ],
        exchangeFeeTemplateId: [
          {
            required: true,
            message: "请选择手续费模板",
            trigger: "change",
          },
        ],
        traderRiskTemplateId: [
          {
            required: true,
            message: "请选择风控模板",
            trigger: "change",
          },
        ],
      },

      nickname: "",
      setId: "",
      setVisible: false,
      setoptions: [],
      setObj: {},

      // 
      batchName: "",
      setdialogVisible: false,
      dynamicValidateForm: {
        groupId: [],
      },
      groupList: [],
      labelLists: [],
      multipleSelectionAll: [],

      searchGroupId: "",
      searchTag: ""
    };
  },
  mounted() {
    traderconfigtemplateGetOption()
      .then((res) => {
        console.log("交易员综合配置模版全列表", res);
        this.traderConfigOptions = res;
      })
      .catch((err) => {
        console.log(err);
      });
    exchangefeetemplateGetOption()
      .then((res) => {
        console.log("交易员手续费模板全列表", res);
        this.exchangeFeeOptions = res;
      })
      .catch((err) => {
        console.log(err);
      });
    traderrisktemplateGetOption()
      .then((res) => {
        console.log("交易员风控模板全列表", res);
        this.traderriskOptions = res;
      })
      .catch((err) => {
        console.log(err);
      });
    datafieldGetOption({})
      .then((res) => {
        console.log("数据场全列表", res);
        this.options = res;
      })
      .catch((err) => {
        console.log(err);
      });
    interfacetype()
      .then((res) => {
        console.log("交易接口全列表", res);
        this.interfacetypeList = res;
      })
      .catch((err) => {
        console.log(err);
      });
    interfaceTrader()
      .then((res) => {
        console.log("交易商全列表", res);
        this.futuresmerchant = res;
      })
      .catch((err) => {
        console.log(err);
      });
    this.getlist();
    console.log(this.selectinterfacetype(1));

    // 分组、标签
    this.groupLists();
    this.getTagList();
  },
  methods: {
    checkPermi,
    // 分组列表
    groupLists() {
      groupListApi({ page: 1, limit: 9999 }).then(async (res) => {
        this.groupList = res.list;
      });
    },
    //标签列表
    getTagList() {
      tagListApi({ page: 1, limit: 9999 }).then((res) => {
        this.labelLists = res.list;
      });
    },
    setBatch(name, row) {
      this.batchName = name;
      if (row) {
        this.userIds = row.id;
        if (this.batchName === "group") {
          this.dynamicValidateForm.groupId = row.groupId
            ? Number(row.groupId)
            : "";
        } else {
          this.dynamicValidateForm.groupId = row.tagId
            ? row.tagId.split(",").map(Number)
            : [];
        }
      } else {
        this.dynamicValidateForm.groupId = "";
      }
      if (this.multipleSelectionAll.length === 0 && !row)
        return this.$message.warning("请选择要设置的用户");
      this.setdialogVisible = true;
    },
    submitForm(formName) {
      console.log(this.dynamicValidateForm, 2222222222)
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.batchName === "group"
            ? masteraccountUpdate({
              groupId: this.dynamicValidateForm.groupId,
              id: this.userIds,
            })
              .then((res) => {

                this.$message.success("设置成功");
                this.loading = false;
                this.handleClose();

                that.$nextTick(function () {
                  that.getlist();
                });
              })
              .catch(() => {
                this.loading = false;
              })
            : masteraccountUpdate({
              tagId: this.dynamicValidateForm.groupId.join(","),
              id: this.userIds,
            })
              .then((res) => {
                this.$message.success("设置成功");
                this.loading = false;

                this.handleClose();

                that.$nextTick(function () {
                  that.getlist();
                });

              })
              .catch(() => {
                this.loading = false;
              });
        } else {
          return false;
        }
      });
    },
    handleClose() {
      this.setdialogVisible = false;
      this.$refs["dynamicValidateForm"].resetFields();
    },
    // 全选
    onSelectTab(selection) {
      this.selectionList = selection;
      setTimeout(() => {
        this.changePageCoreRecordData();
        let data = [];
        if (this.multipleSelectionAll.length) {
          this.multipleSelectionAll.map((item) => {
            data.push(item.uid);
          });
          this.userIds = data.join(",");
        }
      }, 50);
    },
    // 设置选中的方法
    setSelectRow() {
      if (!this.multipleSelectionAll || this.multipleSelectionAll.length <= 0) {
        return;
      }
      // 标识当前行的唯一键的名称
      const idKey = this.idKey;
      const selectAllIds = [];
      this.multipleSelectionAll.forEach((row) => {
        selectAllIds.push(row[idKey]);
      });
      this.$refs.table.clearSelection();
      for (var i = 0; i < this.tableData.data.length; i++) {
        if (selectAllIds.indexOf(this.tableData.data[i][idKey]) >= 0) {
          // 设置选中，记住table组件需要使用ref="table"
          this.$refs.table.toggleRowSelection(this.tableData.data[i], true);
        }
      }
    },
    // 记忆选择核心方法
    changePageCoreRecordData() {
      // 标识当前行的唯一键的名称
      const idKey = this.idKey;
      const that = this;
      // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
      if (this.multipleSelectionAll.length <= 0) {
        this.multipleSelectionAll = this.selectionList;
        return;
      }
      // 总选择里面的key集合
      const selectAllIds = [];
      this.multipleSelectionAll.forEach((row) => {
        selectAllIds.push(row[idKey]);
      });
      const selectIds = [];
      // 获取当前页选中的id
      this.selectionList.forEach((row) => {
        selectIds.push(row[idKey]);
        // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
        if (selectAllIds.indexOf(row[idKey]) < 0) {
          that.multipleSelectionAll.push(row);
        }
      });
      const noSelectIds = [];
      // 得到当前页没有选中的id
      this.tableData.data.forEach((row) => {
        if (selectIds.indexOf(row[idKey]) < 0) {
          noSelectIds.push(row[idKey]);
        }
      });
      noSelectIds.forEach((uid) => {
        if (selectAllIds.indexOf(uid) >= 0) {
          for (let i = 0; i < that.multipleSelectionAll.length; i++) {
            if (that.multipleSelectionAll[i][idKey] == uid) {
              // 如果总选择中有未被选中的，那么就删除这条
              that.multipleSelectionAll.splice(i, 1);
              break;
            }
          }
        }
      });
    },
    setGroup(obj) {
      // let that = this;
      // that.setObj=obj
      // // console.log(that.setId)
      // // console.log(that.setObj)
      // groupListApi({}).then(res => {
      //   that.setoptions = res.list;
      //   // console.log(typeof that.setId)
      //   // that.setId = obj.groupId.toString()
      //   console.log(res)
      // }).catch(res => {
      //   console.log(res)
      // })
      // that.setVisible = true;

    },

    setLabel(obj) {
      console.log(obj)
    },
    sureSet() {
      // let that = this;
      // if (that.setId == "") {
      //   return that.$message.warning("请选择！");
      // }
      // let data=that.setObj;
      // data.groupId=that.setId;
      // // console.log(data)

      // masteraccountUpdate(data)
      //   .then((res) => {
      //     console.log(res);
      //     that.$message.success("设置成功");
      //     that.getlist();
      //     that.setVisible=false;
      //   })
      //   .catch((err) => {
      //     console.log(err);

      //   });
    },
    // 查询表格对应交易接口名称
    selectinterfacetype(id) {
      let face = this.interfacetypeList.find((res) => {
        return res.dictValue == JSON.stringify(id);
      });
      if (face) return face.dictLabel;
    },
    selectUser() {
      this.userVisible = true;
    },
    getTemplateRow(row) {
      this.ruleForm.userId = row.uid;
      this.from.userId = row.uid;
    },
    userclose() {
      this.ruleForm.userId = "";
      this.from.userId = "";
      this.userVisible = false;
    },
    usersubmit() {
      this.userVisible = false;
    },
    search() {
      console.log(this.from);
      // console.log(this.nickname)
      this.from.page = 1;
      this.from.limit = 15;

      console.log('标签数据：', this.searchFrom)

      if (this.searchFrom.tagId.length > 0) {
        // console.log(this.searchFrom.tagId.join(","))
        let tagId=this.searchFrom.tagId.join(",")
        this.from.tagId=tagId
      }


      // return


      this.getlist();
    },
    reset() {
      this.from = {
        status:1,
        account:"",
        page: 1,
        limit: 15,
        // isLogin: 1,
        tagId:"",
        groupId:""
      };
      this.searchFrom.tagId=[]
      this.getlist();
    },
    getlist() {
      this.loading = true;
      masteraccountList(this.from)
        .then((res) => {
          this.tableData.data = res.list;
          this.tableData.total = res.total;

          // console.log('数据：', res)

          this.$nextTick(function () {
            this.setSelectRow(); // 调用跨页选中方法
          });
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    add() {
      this.ruleForm = {};
      this.dialogVisible = true;
    },
    close() {
      this.ruleForm = {};
      this.dialogVisible = false;
    },
    handleCheckedCitiesChange(e) {
      // 单选
      if (e.length === 1) {
        this.ruleForm.tradeTypes = this.checkedCities[0];
      } else {
        // 多选
        this.ruleForm.tradeTypes = 3;
      }
    },

    submit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          // if (
          //   this.ruleForm.account == "" ||
          //   this.ruleForm.account == undefined
          // ) {
          //   return this.$message.warning("请输入用户名！");
          // }
          // if (
          //   this.ruleForm.password == "" ||
          //   this.ruleForm.password == undefined
          // ) {
          //   return this.$message.warning("请输入密码！");
          // }
          // if (
          //   this.ruleForm.authorizationCode == "" ||
          //   this.ruleForm.authorizationCode == undefined
          // ) {
          //   return this.$message.warning("请输入授权码！");
          // }
          // if (
          //   this.ruleForm.interfaceType == "" ||
          //   this.ruleForm.interfaceType == undefined
          // ) {
          //   return this.$message.warning("请选择交易接口！");
          // }
          // if (
          //   this.ruleForm.futuresMerchantId == "" ||
          //   this.ruleForm.futuresMerchantId == undefined
          // ) {
          //   return this.$message.warning("请选择交易商！");
          // }

          if (this.ruleForm.id) {
            console.log("编辑", this.ruleForm);
            masteraccountUpdate(this.ruleForm)
              .then((res) => {
                console.log(res);
                this.close();
                this.$message.success("编辑成功");
                this.getlist();
              })
              .catch((err) => {
                console.log(err);
                this.$message.error(err);
              });
          } else {
            console.log("新增", this.ruleForm);

            // let data = {
            //   account: this.ruleForm.account,
            //   password: this.ruleForm.password,
            //   authorizationCode: this.ruleForm.authorizationCode,
            //   appId: this.ruleForm.appId,
            //   interfaceType: this.ruleForm.interfaceType,
            //   futuresMerchantId: this.ruleForm.futuresMerchantId,

            // };

            masteraccountSave(this.ruleForm)
              .then((res) => {
                console.log(res);
                this.close();
                this.$message.success("新增成功");
                this.getlist();
              })
              .catch((err) => {
                console.log(err);
                this.$message.error(err);
              });
          }
        } else {
          this.$message.error("请填写完整信息");
        }
      });
    },
    // 选择
    onSelectTab(selection) {
      this.selection = [];
      selection.forEach((item) => {
        this.selection.push(item.id);
      });
      console.log(this.selection);
    },
    allDel() {
      if (this.selection.length == 0) {
        return this.$message.error("至少选择一项");
      }
      console.log(this.selection);
      this.$confirm("确认删除？")
        .then((_) => {
          masteraccountDelete(this.selection)
            .then((res) => {
              console.log(res);
              this.$message.success("删除成功");
              this.getlist();
            })
            .catch((err) => {
              console.log(err);
              this.$message.error(err);
            });
        })
        .catch((_) => { });
    },
    exportTable() {
      traderaccountExport(this.from)
        .then((res) => {
          console.log("导出表格", res);
          window.open(res.filename);
        })
        .catch((err) => {
          console.log(err);
          this.$message.error(err);
        });
    },
    handleLogin(row) {
      let masterAccountId = row.id;
      masteraccountLogin({ masterAccountId }).then((res) => {
        console.log("登录", res);
        // this.$message.success("登录成功");
        this.getLoginType(masterAccountId);
      });
    },
    handleLogout(row) {
      let masterAccountId = row.id;
      masteraccountLogout({ masterAccountId }).then((res) => {
        console.log("退出", res);
        this.$message.success("登出请求已发送，请稍等");
        // this.getLoginType(masterAccountId);
      });
    },
    getLoginType(masterAccountId) {
      // console.log(this.masteraccountLoginForm, 2222, masterAccountId);
      if (masterAccountId)
        this.masteraccountLoginForm.masterAccountId = masterAccountId;
      getLoginInfo({
        masterAccountId: this.masteraccountLoginForm.masterAccountId,
      }).then(
        (res) => {
          let that = this;
          console.log("🚀🚀🚀 ~ resendVerifyCode ~ res:", that);
          if (this.masteraccountVisible) {
          } else {
            console.log("获取登录信息并发送验证码", res);
            if (res.loginStatus == 2 && res.secondVerify == false) {
              console.log(
                "🚀🚀🚀 ~ getLoginType ~ this.sendLoading:",
                this.sendLoading
              );
              if (!this.sendLoading) {
                this.sendLoading = this.$loading({
                  lock: true,
                  text: "登录中请稍后",
                  spinner: "el-icon-loading",
                  background: "rgba(0, 0, 0, 0.7)",
                });
              }
              // if (this.smsTimer == null) this.setTime();
              if (this.loginTimer == null) this.setLoginTime();
            } else if (res.loginStatus == 2 && res.secondVerify == true) {
              if (this.sendLoading) {
                this.sendLoading.close();
                console.log(
                  "🚀🚀🚀 ~ getLoginType ~ this.sendLoading:",
                  this.sendLoading
                );
              }
              if (this.smsTimer == null) this.setTime();
              if (this.loginTimer) clearInterval(this.loginTimer);
              this.$message.success("验证码已发送，请输入验证码");
              this.masteraccountVisible = true;
              this.masteraccountLoginForm.phone = res.contactInfo;
              // masteraccountVerify({
              //   masterAccountId:
              //     masterAccountId || this.masteraccountLoginForm.masterAccountId,
              // }).then((res) => {
              //   console.log("🚀🚀🚀 ~ resendVerifyCode ~ res:", res);
              // });
            } else if (res.loginStatus == 1) {
              console.log("成功登录");
              if (this.sendLoading) {
                this.sendLoading.close();
              }
              console.log(
                "🚀🚀🚀 ~ getLoginType ~ this.sendLoading:",
                this.sendLoading
              );

              this.stopTimer();
              this.$message.success("登陆成功");
              this.getlist();
            } else if (res.loginStatus == 3) {
              console.log("登陆失败");
              if (this.sendLoading) {
                this.sendLoading.close();
              }
              this.stopTimer();
              this.getlist();
              this.$message.success("登陆失败");
            }
          }
        },
        (err) => {
          if (this.sendLoading) {
            this.sendLoading.close();
          }
          this.stopTimer();
          Message.error(err);
        }
      );
    },
    //验证码发送
    async sendMsg() {
      if (this.countdown == 60) {
        let res = await resendVerifyCode({
          masterAccountId: this.masteraccountLoginForm.masterAccountId,
        });
        if (res.code == 200) {
          Message.success("验证码已发送，有效期十分钟");
        }
      }
    },
    loginSubmit() {
      // this.userVisible = false;
      if (this.masteraccountLoginForm.verifyCode) {
        masteraccountVerify(this.masteraccountLoginForm).then((res) => {
          this.loginLoading = true;
          console.log("实盘登录输入验证码", res);
          this.$message.success("验证码提交，请等待");
          this.setLoginTime();
        });
      } else {
        this.$message.error("请输入验证码");
      }
    },
    loginClose() {
      let that = this;
      clearInterval(this.loginTimer);
      clearInterval(this.smsTimer);
      this.loginTimer = null;
      this.smsTimer = null;
      this.masteraccountVisible = false;
      this.$message.warning("已取消登录");
      console.log(this.loginTimer);
      // setTimeout(() => {
      //   that.masteraccountVisible = false;
      // }, 10000);
    },
    setTime() {
      let that = this;
      this.smsTimer = setInterval(function () {
        that.countdown--;
        // that.getLoginType();
        if (that.countdown == 0) {
          clearInterval(that.smsTimer);
          that.loginLoading = false;
          that.countdown = 60;
        }
      }, 1000);
    },
    setLoginTime() {
      let that = this;
      this.loginTimer = setInterval(function () {
        that.getLoginType();
        that.loginTimeCount++;
        // that.loginLoading = true;
        if (that.loginTimeCount == 20) {
          clearInterval(that.loginTimer);
          that.loginTimeCount = 0;
          that.loginLoading = false;
          that.sendLoading.close();
          Message.warning("登录超时，请重新登录");
        }
      }, 2000);
    },
    stopTimer() {
      clearInterval(this.loginTimer);
      this.loginTimer = null;
      clearInterval(this.smsTimerTimer);
      this.smsTimer = null;
      // this.countdown = 60;
      this.masteraccountLoginForm = {
        loginType: 2,
      };
      // this.loginLoading = false;
    },
    handleVerify(row) {
      console.log("验证", row);
      masteraccountVerify({ masterAccountId: row.id }).then((res) => {
        console.log("验证", res);
        this.$message.success("验证成功");
      });
    },
    handleResend(row) {
      console.log("重发", row);
      resendVerifyCode({ masterAccountId: row.id }).then((res) => {
        console.log("重发", res);
        this.$message.success("重发成功");
      });
    },
    handleWallet(row) {
      console.log("出入金", row);
      this.mform.traderAccountId = row.id;
      this.mVisible = true;
    },
    handleInterface(row) {
      console.log("接口", row);
      this.interfaceVisible = true;
      interfaceTrader;
      this.masteraccountVisible = true;
    },
    mClose() {
      this.walletResponses = [];
      this.mform = {
        traderAccountId: "",
        inOutType: "",
        walletResponses: [],
        currencyId: "",
        amount: "",
      };
      this.mVisible = false;
    },
    mSubmit() {
      this.$refs["mform"].validate((valid) => {
        if (valid) {
          console.log("出入金信息", this.mform);
          let data = {
            traderAccountId: this.mform.traderAccountId,
            currencyId: this.mform.currencyId,
            inOutType: this.mform.inOutType,
            amount: this.mform.amount,
          };
          traderaccountInOutType(data)
            .then((res) => {
              console.log(res);
              this.mClose();
              this.$message.success("成功");
              this.getlist();
            })
            .catch((err) => {
              console.log(err);
              this.$message.error(err);
            });
        } else {
          this.$message.error("请填写完整信息");
        }
      });
    },
    handleEdit(row) {
      console.log("编辑", row);
      masteraccountInfo(row.id)
        .then((res) => {
          console.log("详情", res);
          this.ruleForm = res;
          this.ruleForm.interfaceType = JSON.stringify(res.interfaceType);
          this.dialogVisible = true;
        })
        .catch((err) => {
          console.log(err);
          this.$message.error(err);
        });
    },
    handleDel(row) {
      this.$confirm("确认删除？")
        .then((_) => {
          console.log("删除", row);
          masteraccountDelete([row.id])
            .then((res) => {
              console.log(res);
              this.$message.success("删除成功");
              this.getlist();
            })
            .catch((err) => {
              console.log(err);
              this.$message.error(err);
            });
        })
        .catch((_) => { });
    },
    pageChange(page) {
      this.from.page = page;
      this.getlist();
    },
    handleSizeChange(val) {
      this.from.limit = val;
      this.getlist();
    },
  },
};
</script>

<style scoped lang="scss">
.btn_bt {
  border-top: 1px dashed #ccc;
  padding-top: 20px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
  font-size: 14px;
  margin-left: 15px;
}

.m-left-20 {
  margin-left: 20px;
}
</style>
